package com.atguigu.yygh.order.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.enums.RefundStatusEnum;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.order.RefundInfo;
import com.atguigu.yygh.order.mapper.OrderMapper;
import com.atguigu.yygh.order.mapper.RefundInfoMapper;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.RefundService;
import com.atguigu.yygh.order.utils.ConstantPropertiesUtils;
import com.atguigu.yygh.order.utils.HttpClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: TODO
 * @author: 化一帆
 * @date: 2022/12/11 19:39
 * @version: v1.0
 */
@Service
public class RefundServiceImpl extends ServiceImpl<RefundInfoMapper, RefundInfo> implements RefundService {

        @Autowired
        PaymentService paymentService;


        @Override
        public boolean refund(Long orderId) {

//        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
            PaymentInfo paymentInfo = paymentService.getPaymentByOrderId(orderId);

            //1、创建退款记录
            //查询该订单的退款记录
            QueryWrapper<RefundInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id",orderId);
            RefundInfo refundInfo = baseMapper.selectOne(queryWrapper);

            if(refundInfo==null){
                //根据支付记录，创建退款记录
                refundInfo = new RefundInfo();

                refundInfo.setOutTradeNo(paymentInfo.getOutTradeNo());
                refundInfo.setOrderId(paymentInfo.getOrderId());
                refundInfo.setPaymentType(paymentInfo.getPaymentType());

//            refundInfo.setTradeNo();退款成功后，微信端返回的退款流水号
//            refundInfo.setCallbackTime(); 回调时间（退款成功后，赋值）
//            refundInfo.setCallbackContent();  微信端返回的所有数据（map.toString）

                refundInfo.setTotalAmount(paymentInfo.getTotalAmount());
                refundInfo.setSubject(paymentInfo.getSubject());
                refundInfo.setRefundStatus(RefundStatusEnum.UNREFUND.getStatus());//退款中（未退款）

                baseMapper.insert(refundInfo);
            }

            //2、调用微信接口退钱

            String url = "https://api.mch.weixin.qq.com/secapi/pay/refund";

            Map<String,String> paramMap = new HashMap<>();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            paramMap.put("out_trade_no",paymentInfo.getOutTradeNo());
            paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo());
            paramMap.put("total_fee","1");//付款金额
//        paramMap.put("total_fee",paymentInfo.getTotalAmount().multiply(new BigDecimal(100)).intValue()+"");
            paramMap.put("refund_fee","1");//退款金额

            try {
                String xmlParam = WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY);

                HttpClient httpClient = new HttpClient(url);
                httpClient.setHttps(true);
                httpClient.setXmlParam(xmlParam);
                httpClient.setCert(true);//需要证书
                httpClient.setCertPassword(ConstantPropertiesUtils.PARTNER);
                httpClient.post();

                //微信端的返回值
                String content = httpClient.getContent();
                Map<String, String> responseMap = WXPayUtil.xmlToMap(content);

                //退款成功后，修改refundInfo（退款记录）三个字段
                String result_code = responseMap.get("result_code");
                if("SUCCESS".equalsIgnoreCase(result_code)){
                    refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());//2,已退款
                    refundInfo.setTradeNo(responseMap.get("transaction_id"));//退款成功后，流水号
                    refundInfo.setCallbackTime(new Date());
                    refundInfo.setCallbackContent(responseMap.toString());
                    baseMapper.updateById(refundInfo);
                }else {
                    throw new YyghException(20001,"退款失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return false; //加上
//            throw
            }

            return true;
        }


    }

